package com.zhongxi.guoyuan.view.beautifulStore;

import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.beautifulOrder.BeautifulStoreOrderData;
import com.zhongxi.guoyuan.entity.gift.RecommentResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

import static com.zhongxi.guoyuan.url.Url.RECOMMENT_SHARE;

public class BeautifulCommentActivity extends BaseActivity implements View.OnClickListener {

    public static final int RESULTCODECOMMEND = 3;
    private BeautifulStoreOrderData list;


    private Map<String, String> map = new HashMap<>();
    private String star_sja = "1";

    private ImageView ivImage;
    private TextView tvTime;
    private TextView tvProjectName;
    private TextView tvOriginPrice;
    private TextView tvCash;
    private TextView tvView;
    private TextView workmanship;


    private EditText etTips_fuwu;
    private TextView tvNum_fuwu;
    private RatingBar rb_sja;
    private RatingBar rb_fuwu;

    private EditText etTips_sja;
    private TextView tvNum_sja;
    private Button btSubscribe;
    private String star_xm = "1";
    private String content_fuwu;
    private String content_sja;
    private String type;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_beautiful_comment);
        initTitle();
        tvTitle.setText("美容评价");
        Intent intent = getIntent();
        list = (BeautifulStoreOrderData) intent.getSerializableExtra("info");


        ivImage= (ImageView) findViewById(R.id.ivImg);
        tvTime= (TextView) findViewById(R.id.tvTime);
        tvProjectName= (TextView) findViewById(R.id.tvProjectName);
        tvOriginPrice= (TextView) findViewById(R.id.tvOriginPrice);
        tvOriginPrice.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        tvCash= (TextView) findViewById(R.id.tvCash);
        tvView= (TextView) findViewById(R.id.tvView);
        workmanship= (TextView) findViewById(R.id.workmanship);


        etTips_fuwu = (EditText) findViewById(R.id.etTips_fuwu);
        tvNum_fuwu = (TextView) findViewById(R.id.tvNum_fuwu);
        rb_fuwu= (RatingBar) findViewById(R.id.rb_fuwu);


        rb_sja = (RatingBar) findViewById(R.id.rb_sja);
        etTips_sja = (EditText) findViewById(R.id.etTips_sja);
        tvNum_sja = (TextView) findViewById(R.id.tvNum_sja);
        btSubscribe = (Button) findViewById(R.id.btSubscribe);

        setData();
    }

    /**
     * 初始化数据
     */
    private void setData() {

        if(null!=list.getThumbnail()&&!"".equals(list.getThumbnail())){
            Glide.with(context).load(Url.IMG_URL + list.getThumbnail()).placeholder(R.mipmap.iv_eg).into(ivImage);
        }
        if(null!=list.getItemname()&&!"".equals(list.getItemname())){
            tvProjectName.setText(list.getItemname());
        }else{
            tvProjectName.setText("");
        }
        if(null!=list.getServicetime()&&!"".equals(list.getServicetime())){
            tvTime.setText(list.getServicetime()+"分钟");
        }else{
            tvTime.setText("");
        }
        if(null!=list.getMarketprice()&&!"".equals(list.getMarketprice())){
            tvOriginPrice.setText("市场价："+list.getMarketprice()+"元");
        }else{
            tvOriginPrice.setText("市场价："+list.getMarketprice()+"元");
        }

        if(null!=list.getShouldinnerprice()&&!"".equals(list.getShouldinnerprice())){
         tvCash.setText(list.getShouldinnerprice()+"美豆");
        }else{
            tvCash.setText("");
        }

        if(null!=list.getShouldredbeanprice()&&!"".equals(list.getShouldredbeanprice())){
            workmanship.setText("+"+list.getShouldredbeanprice()+"红豆");
        }else{
            workmanship.setText("");
        }

        if(null!=list.getViewnum()&&!"".equals(list.getViewnum())){
            tvView.setText(list.getViewnum());
        }else{
            tvView.setText("");
        }

    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        btSubscribe.setOnClickListener(this);
        rb_fuwu.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                star_xm = rating + "";

            }
        });

        rb_sja.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                star_sja = rating + "";

            }
        });

        etTips_fuwu.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void afterTextChanged(Editable editable) {
                MyTextUtils.TextChangeUtils(context, tvNum_fuwu, editable, 200);
            }
        });

        etTips_sja.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void afterTextChanged(Editable editable) {
                MyTextUtils.TextChangeUtils(context, tvNum_sja, editable, 200);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.btSubscribe:
                if (!MyTextUtils.isFastDoubleClick()) {
                    content_fuwu = etTips_fuwu.getText().toString().trim();
                    content_sja = etTips_sja.getText().toString().trim();
                    if (TextUtils.isEmpty(content_fuwu) || TextUtils.isEmpty(content_sja)) {
                        showShortToast("评论内容不能为空！");
                    } else {
                        toComment();
                    }
                }
                break;
        }
    }

    /**
     * 评论
     */
    private void toComment() {
        type = "tocomment";
        map.clear();
        String params = "{\"item\":{\"orderid\":\"" + list.getId() + "\",\"sid\":\"" + list.getItemid() + "\",\"starlevel\":\"" + star_xm + "\",\"content\":\"" + content_fuwu + "\"}," +
                "\"store\":{\"starlevel\":\"" + star_sja + "\",\"content\":\"" + content_sja + "\"}}";
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(params);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put("comments", jsonObject.toString());
        Log.d("flag", "toComment: "+jsonObject.toString());
        getServer(Url.INNER_COMMENT, map, "", false, null, "post");
    }

    private void showRecomment() {
        type="recomment";
        getServer(Url.RECOMMENT_SHARE, null, "", false, null, "get");
    }

    private String getJsonParams() {
        JSONObject object = new JSONObject();
        try {
            JSONObject jsonItem = new JSONObject();
            jsonItem.put("orderid", list.getId());
            jsonItem.put("sid", list.getShopid());
            jsonItem.put("starlevel", star_xm);
            jsonItem.put("content", content_fuwu);
            JSONObject jsonStore = new JSONObject();
            jsonStore.put("starlevel", star_sja);
            jsonStore.put("content", content_sja);

            object.put("item", jsonItem);
            object.put("store", jsonStore);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object.toString();
    }

    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        if ("tocomment".equals(type)) {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            MyApplication.getInstance().setSpValue(result.getSafeobj());
            showShortToast("评论成功");

            setResult(RESULTCODECOMMEND);
            finish();

           // showRecomment();
        }else if ("recomment".equals(type)){
            RecommentResult result = gson.fromJson(response, RecommentResult.class);
            MyApplication.getInstance().setSpValue(result.getSafeobj());
//            if (result.getData() != null && result.getData().getActivity() != null) {
//                Intent intent = new Intent(BeautifulCommentActivity.this, CommentSuccessActivity.class);
//                intent.putExtra("data", result.getData());
//                startActivity(intent);
//
//            } else {
//                showPopupWindow();
//            }
        }
    }

    private void showPopupWindow() {
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            View layout = LayoutInflater.from(context).inflate(R.layout.dialog_comment_noshare, null);
            builder.setView(layout);
            final AlertDialog dialog = builder.create();
            dialog.show();
            TextView tvSurePay = (TextView) layout.findViewById(R.id.tvSure);
            TextView tvContent = (TextView) layout.findViewById(R.id.tvContent);
            ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
            ivCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    setResult(RESULTCODECOMMEND);
                    finish();
                }
            });
            tvSurePay.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    setResult(RESULTCODECOMMEND);
                    finish();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if (null != result.getSafeobj() && !"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        if (1020 == result.getCode()) {
            showShortToast("评论服务暂不可用");
        } else {
            showShortToast("评论失败");
        }
    }

}
